/**
 * Created by tanbingqin on 2019/4/28.
 */
import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Input, Tabs, Spin, Row, Col, Icon, message, Select, Tag } from 'antd'
import constants from 'share/constants'
const TabPane = Tabs.TabPane;
const Search = Input.Search;

import moment from 'moment'
import debounce from 'lodash.debounce'
import 'styles/request/travel-request/comp/location.scss'
import travelService from 'containers/request/travel-request/travel.service'

class TravelLocation extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      value: props.mode === 'single' ? (props.isEntity ? {} : '') : [],
      nowTab: 'domestic',
      isShowSearch: false,
      isLoadingSearch: false, //是否正在loading搜索
      isLoadingHistory: false, //是否正在loading历史数据
      keyword: '', //搜索的关键字
      keywordDelay: '', //延迟的搜索关键字，因为搜索接口debounce了，高亮处也要使用延迟的关键字
      searchData: [], //搜索结果列表
      historyData: [] //地点控件历史数据，存在前端localStorage里，存最新的三个
    };
    this.handleSearchStep2 = debounce(this.handleSearchStep2, 500);
  }

  componentDidMount() {
    let { value, isEntity, mode } = this.props;
    if (value && isEntity && mode === 'single') {
      value.adCode = value.code ? value.code: value.adCode;
      value.adName = value.vendorAlias ? value.vendorAlias : value.adName;
    }
    this.setState({value});
    this.initHistoryData();
  };

  componentWillReceiveProps(nextProps) {
    let value = nextProps.value;
    if (value && nextProps.isEntity && nextProps.mode === 'single') {
      value.adCode = value.code ? value.code: value.adCode;
      value.adName = value.vendorAlias ? value.vendorAlias : value.adName;
    }
    this.setState({value});
    this.initHistoryData();
  };

  //初始化历史选择数据
  initHistoryData = (isNeedCheckLanguage) => {
    let historyDataStr = localStorage.getItem('hly.travel.city.history');
    if(historyDataStr && JSON.parse(historyDataStr)){
      this.setState({historyData: JSON.parse(historyDataStr)}, () => {
        if (isNeedCheckLanguage) {
          this.judgeHistoryLanguage();
        }
      });
    } else {
      this.setState({historyData: []});
    }
  };

  //校验历史选择的数据的语言是否是当前语言，如果不一致，需要刷新历史数据
  judgeHistoryLanguage = () => {
    const { historyData } = this.state;
    const { language } = this.props;
    if (historyData && historyData.length && historyData[0].languageCode !== language.code) {
      let historyCityCodeList = [];
      historyData.map(history => {
        historyCityCodeList.push(history.adCode);
      });
      this.setState({isLoadingHistory: true});
      travelService.searchCitiesByCode(historyCityCodeList, language.code).then(res => {
        let newHistoryData = [];
        res.data && res.data.map(newHistory => {
          newHistoryData.push({
            code: newHistory.adCode,
            vendorAlias: newHistory.adName,
            adCode: newHistory.adCode,
            adName: newHistory.adName,
            languageCode: language.code
          });
        });
        this.setState({historyData: newHistoryData});
        localStorage.setItem('hly.travel.city.history', JSON.stringify(newHistoryData));
      }).finally(() => {
        this.setState({isLoadingHistory: false});
      });
    }
  };

  renderTabs = () => {
    const { formCode } = this.props;
    let tabs = [
      {key: 'domestic', name: messages('request.key355')/*国内*/}
    ];
    if (['MCD1001','MCD4001','MCD3001'].indexOf(formCode) < 0) {
      tabs.push({key: 'international', name: messages('request.key356')/*国际*/});
    }
    return (
      tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key} disabled={tab.disabled}/>
      })
    )
  };

  //Tabs点击
  onChangeTabs = (key) => {
    const { intEnable } = this.props;
    if (!intEnable && key === 'international') {
      message.error(messages('request.key573')/*当前选择的供应商不支持国际地点！*/);
      return;
    }
    this.setState({nowTab: key, keyword: '', keywordDelay: '', searchData: []});
  };

  onChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  };

  handleShowSearchBlock = (isFocus) => {
    if (this.props.disabled) return;
    if (isFocus) {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.setState({
        isShowSearch: true
      }, this.initHistoryData(true));//此处获取焦点只能做不会变动的数据初始化，不然input search切换焦点时数据会有问题
    } else {
      this.timer = setTimeout(() => {
        this.setState({
          isShowSearch: false
        }, () => this.resetAll());
      }, 100);
    }
  };

  //在失焦后重置搜索展示框
  resetAll = () => {
    this.setState({nowTab: 'domestic', keyword: '', keywordDelay: '', searchData: []});
  };

  handleSearch = (value) => {
    this.setState({keyword: value, isLoadingSearch: true});
    this.handleSearchStep2(value);
  };

  handleSearchStep2 = (value) => {
    const { nowTab } = this.state;
    const { language, vendorType } = this.props;
    this.setState({keywordDelay: value});
    if (value) {
      let country = nowTab === 'international' ? 'all' : 'china';
      let city = [];
      travelService.searchCitiesV2(vendorType, value, country, language.code === 'zh_cn' ? 'zh_cn' : 'en').then(res => {
        if (res.data && res.data.length) {
          res.data.forEach(item => {
            const { adCode } = item;
            if (!constants.provinceCode.includes(adCode)) {
              city.push(item)
            }
          })
          this.setState({searchData: city, isLoadingSearch: false});
        }else {
          this.setState({searchData: [], isLoadingSearch: false});
        }
      });
    } else {
      this.setState({searchData: [], isLoadingSearch: false});
    }
  };

  handleClear = () => {
    const { isEntity } = this.props;
    if (isEntity) {
      this.setState({value: {}}, () => {
        this.onChange();
        this.props.onSelect({});
      });
    } else {
      this.setState({value: ''}, () => {
        this.onChange('');
        this.props.onSelect({});
      });
    }
  };

  brightenKeyword = (val) => {
    const { keywordDelay } = this.state;
    val = val + '';
    if (val.indexOf(keywordDelay) !== -1 && keywordDelay !== '') {
      return val.replace(keywordDelay, '<span style="color: #1E78C8">' + keywordDelay + '</span>')
    } else {
      return val
    }
  };

  //city选中的数据对象，isFromHistory bool是否是从历史列表中选中的，历史数据要进行额外校验
  handleSelect = (city, isFromHistory) => {
    const { vendorType, intEnable } = this.props;
    if (!city.vndStatus && !isFromHistory) {
      //供应商不支持该地点
      return;
    }
    if (isFromHistory) {
      travelService.isCityInVendor(vendorType, city.adCode, intEnable ? 'all' : 'china').then(res => {
        if(res.data && res.data.alias){
          this.doHandleSelect(city);
        } else {
          message.error(messages('request.key574')/*当前选择的供应商不支持该地点！*/);
        }
      }).catch(err => {
        message.error(messages('request.key574')/*当前选择的供应商不支持该地点！*/);
      });
    } else {
      this.doHandleSelect(city);
    }
  };

  doHandleSelect = (city) => {
    const { isEntity, isOldDataType, mode, language } = this.props;
    let { value } = this.state;
    if (mode === 'single') {
      value = isEntity ? city : city.adName;
    }
    if (mode === 'multiple') {
      if (value && value.length) {
        value.addIfNotExistObj({label: city.adName, key: city.adCode}, 'key');
      } else {
        value = [{label: city.adName, key: city.adCode}];
      }
    }
    this.setState({ value }, () => {
      let { value } = this.state;
      //多选模式下手动失焦，不会在选完一个数据后关闭列表页，因为用户还会要再选
      mode === 'single' && this.handleShowSearchBlock(false);
      this.onChange(value);
      let resultCity = {};
      if (isOldDataType) {
        resultCity.code = city.adCode;
        resultCity.vendorAlias = city.adName;
        resultCity.adCode = city.adCode;
        resultCity.adName = city.adName;
      } else {
        resultCity = JSON.parse(JSON.stringify(city));
      }
      resultCity.languageCode = language.code;
      this.processHistory(resultCity);
      this.props.onSelect(resultCity);
    });
  };

  processHistory = (resultCity) => {
    const { historyData } = this.state;
    let resultHistoryData = [];
    resultHistoryData.push(resultCity);
    historyData.map((item, index) => {
      if (resultHistoryData.length < 7) {
        resultHistoryData.addIfNotExistObj(item, 'adCode');
      }
    });
    localStorage.setItem('hly.travel.city.history', JSON.stringify(resultHistoryData));
  };

  //渲染历史选择
  renderHistoryData = () => {
    const { keyword, keywordDelay, historyData, isLoadingHistory } = this.state;
    let historyDataLength = historyData.length;
    return keyword || keywordDelay || !historyDataLength ? (<div />) : (
      <Spin spinning={isLoadingHistory}>
        <div className="history-block">
          <Row>
            <Col span={12} className="left-title">{messages('request.key575')/*历史*/}</Col>
            <Col span={12} className="right-title">
            <span className="delete-icon" onClick={this.clearHistory}>
              <Icon type="delete" />&nbsp; {messages('request.key576')/*清空历史*/}
            </span>
            </Col>
          </Row>
          {historyData.map((history, index) => {
            return (
              <div key={history.adCode}
                   className={`city-item-block ${index !== historyDataLength - 1 ? 'has-bottom' : ''}`}
                   onClick={() => this.handleSelect(history, true)}>
                <div className="title">{history.adName}</div>
              </div>
            )
          })}
        </div>
      </Spin>
    );
  };

  clearHistory = () => {
    this.setState({historyData: []});
    localStorage.setItem('hly.travel.city.history', '');
  };

  //渲染搜索结果
  renderSearchResult = () => {
    const { searchData, isLoadingSearch, keywordDelay } = this.state;
    let searchDataLength = searchData.length;
    return (
      <Spin spinning={isLoadingSearch}>
        <div style={{overflowY: 'auto', maxHeight: 160}}>
          {searchData.map((item, index) => {
            return (
              <div key={item.adCode}
                   className={`city-item-block ${index !== searchDataLength - 1 ? 'has-bottom' : ''} ${!item.vndStatus ? 'not-allowed' : ''}`}
                   onClick={() => this.handleSelect(item)}>
                <Row type="flex" align="middle">
                  <Col span={16}>
                    <div className="title" dangerouslySetInnerHTML={{__html: this.brightenKeyword(item.adName)}}></div>
                    {/*国内外展示路径*/}
                    <div className="sub-title" dangerouslySetInnerHTML={{__html: this.brightenKeyword(item.path)}}></div>
                  </Col>
                  <Col span={7} className="tag">{item.adTypeName}</Col>
                </Row>
                {!item.vndStatus && (
                  <Row style={{lineHeight: '20px'}}>
                    <span className="warning-info">
                      <Icon type="exclamation-circle-o" />&nbsp; {messages('request.key577')/*该供应商不支持该地点*/}
                    </span>
                  </Row>
                )}
              </div>
            )
          })}
          {!searchData.length && keywordDelay && (
            <div style={{marginBottom: 8}}>
              {messages('request.key578')/*抱歉，没有帮您找到符合条件的结果*/}
            </div>
          )}
        </div>
      </Spin>
    )
  };

  renderPlaceHolder = () => {
    const { isFlight } = this.props;
    const { nowTab } = this.state;
    let placeholder = nowTab === 'international' ? messages('request.key579')/*国际·港澳台*/ : messages('request.key580')/*国内·港澳台*/;
    if (isFlight) {
      placeholder = messages('request.key581')/*北京/beijing/bj*/;
    }
    return placeholder;
  };

  //多选模式下清空某一个选项
  removeValue = (e, index) => {
    e.preventDefault();
    let { value } = this.state;
    value.splice(index, 1);
    this.setState({ value }, () => {
      let { value } = this.state;
      this.onChange(value);
    });
  };

  render() {
    const { isShowSearch, nowTab, value, keyword } = this.state;
    const { isEntity, mode, placeHolder, disabled } = this.props;
    let valueForShow = isEntity ? (value ? value.adName : '') : value;
    return (
      <div className="travel-location">
        {mode === 'single' && (
          <div
            tabIndex="1"
            className={`fake-input ${disabled ? 'fake-input-disabled' : ''}`}
            onFocus={() => this.handleShowSearchBlock(true)}
            onBlur={() => this.handleShowSearchBlock(false)}
          >
            {!!valueForShow ? (
              <span>
                <span className="show-txt-block">{valueForShow}</span>
                {
                  !disabled && <span className="show-txt-block-icon">
                    <Icon type="close-circle-o" style={{cursor: 'pointer'}} onClick={this.handleClear}/>
                  </span>
                }
              </span>
              ) : (
                <span style={{color: '#bebdbf'}}>{placeHolder || messages('common.select')/*请选择*/}</span>
              )}
          </div>
        )}
        {mode === 'multiple' && (
          <div
            tabIndex="1"
            className={`fake-input ${disabled ? 'fake-input-disabled' : ''}`}
            onFocus={() => this.handleShowSearchBlock(true)}
            onBlur={() => this.handleShowSearchBlock(false)}
          >
            {value && !!value.length && value.map((item, index) => {
              return (
                <Tag closable onClose={(e) => this.removeValue(e, index)}>
                  {item.label}
                </Tag>
              )
            })}
            {(!value || !value.length) && (
              <span style={{color: '#bebdbf'}}>{placeHolder || messages('common.select')/*请选择*/}</span>
            )}
          </div>
        )}
        {isShowSearch && (
          <div className="drop-down-block"
               tabIndex="1"
               onFocus={() => this.handleShowSearchBlock(true)}
               onBlur={() => this.handleShowSearchBlock(false)}>
            <div>
              <Tabs onChange={this.onChangeTabs} activeKey={nowTab}>
                {this.renderTabs()}
              </Tabs>
              <Search placeholder={this.renderPlaceHolder()}
                      value={keyword}
                      onChange={(e) => this.handleSearch(e.target.value)}/>
              {this.renderHistoryData()}
              {this.renderSearchResult()}
            </div>
          </div>
        )}
      </div>
    )
  }
}

TravelLocation.propTypes = {
  intEnable: React.PropTypes.bool, //是否可选到国际
  vendorType: React.PropTypes.string, //识别供应商
  placeHolder: React.PropTypes.string, //传入的提示语
  mode: React.PropTypes.string, //单选还是多选模式，默认单选  single  multiple
  isEntity: React.PropTypes.bool, //true 绑定到value上的是city obj，为false 绑定到value上的是city name string  仅单选模式适用
  formCode:  React.PropTypes.string, //表单的formCode
  onSelect: React.PropTypes.func, //选中一个city的回调，返回整个city obj
  isOldDataType: React.PropTypes.bool, //返回的city obj的数据格式是不是按老的数据格式返回 仅单选模式适用
  isFlight: React.PropTypes.bool, //是否是机票行程，机票行程的placeholder跟其他行程不一样
  disabled: React.PropTypes.bool
};

// isOldDataType true
// city: {
//   code: '',
//   adCode: '',
//   vendorAlias: '',
//   adName: ''
// }

TravelLocation.defaultProps={
  intEnable: true,
  vendorType: 'standard',
  placeHolder: '',
  mode: 'single',
  isEntity: true,
  formCode: '',
  onSelect: () => {},
  isOldDataType: false,
  isFlight: false,
  disabled: false,
};

function mapStateToProps(state) {
  return {
    language: state.main.language
  }
}

export default connect(mapStateToProps)(TravelLocation);
